package com.jml.强软弱虚引用;


import java.io.IOException;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.util.ArrayList;

/**
 * @author:jml
 * @date: 2019/5/8 15:30
 * @description：
 */
public class 软引用 {

    public static void softRef_Memory_Enough() {
        //强引用
        Object o1 = new Object();
        //软引用
        SoftReference<Object> softReference = new SoftReference<>(o1);
        System.out.println(o1);
        System.out.println(softReference.get());
        o1=null;
        System.gc();
        System.out.println(o1);
        System.out.println(softReference.get());

    }

    //-Xmx5m -Xms5m -XX:+PrintGCDetails
    public static void softRef_Memory_NotEnough() {
        //强引用
        Object o1 = new Object();
        //软引用
        SoftReference<Object> softReference = new SoftReference<>(o1);
        System.out.println(o1);
        System.out.println(softReference.get());
        o1=null;
        try {
           byte[] bytes = new byte[1024*1024*30];
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println(o1);
            System.out.println(softReference.get());
        }
    }

    public static void main(String[] args) {
        //softRef_Memory_Enough();

        softRef_Memory_NotEnough();
    }


    public static void main001(String[] args) throws IOException {
        soft();
    }

    /**
     * 软引用
     */
    private static void soft() {
        ReferenceQueue<byte[]> referenceQueue = new ReferenceQueue<>();
        ArrayList<SoftReference<byte[]>> objects = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            SoftReference<byte[]> softReference = new SoftReference<>(new byte[4 * 1024 * 1024], referenceQueue);
            objects.add(softReference);
        }
        Reference<? extends byte[]> poll = referenceQueue.poll();
        while (poll != null) {
            objects.remove(poll);
            poll = referenceQueue.poll();
        }
        System.out.println("打印结果:");
        objects.forEach((t) -> {
            System.out.println(t.get());
        });
    }



}
